package kayao.client.network.login;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class StrikeSender {

	protected DatagramPacket mPacket=null;
	protected DatagramSocket mSocket=null;
	protected int mTimeout=0;
	protected int mClientToNotifyId=0;
	protected int mRetries=0;
	protected int mAttemps=0;
	protected boolean mAlive=true;
	protected boolean mDone=false;
	
	public StrikeSender(int id,DatagramPacket p,DatagramSocket s,int t,int r)
	{
		mClientToNotifyId=id;
		mPacket=p;
		mSocket=s;
		mRetries=r;
		mTimeout=t;
		//config the socket with the timeouts
		try {
			mSocket.setSoTimeout(mTimeout);
		}
		catch (SocketException e) 
		{
			System.out.println("Error in StrikeSender: SocketException (timeout set): "+e.getMessage());
			e.printStackTrace();
		}
	}
	public boolean isAlive()
	{
		return mAlive;
	}
	public boolean isDone()
	{
		return mDone;
	}
	public DatagramPacket goOnce()
	{
		DatagramPacket p=new DatagramPacket(new byte[50], 50);
		try {
			mSocket.send(mPacket);
			try 
			{
				mSocket.receive(p);
				mAlive=false;
				mDone=true;
				System.out.println("Got reply from client " + mClientToNotifyId);
				return p;
			} 
			catch (IOException e) 
			{
				// Socket timed out
				mAttemps++;
				if(mRetries==mAttemps)
				{
					mAlive=false;
					System.out.println("Client " + mClientToNotifyId + " is considered dead.");
				}
				else System.out.println("Client " + mClientToNotifyId + ", Strike: "+ mAttemps);
				return null;
			}
		} catch (IOException e1) {
			e1.printStackTrace();
			System.out.println("Error in StrikeSender: goOnce (sending packet): "+e1.getMessage());
			return null;
		}
	}
}
